package org.fu.crowd.service.impl;

import org.fu.crowd.mapper.AddressPOMapper;
import org.fu.crowd.mapper.OrderPOMapper;
import org.fu.crowd.mapper.OrderProjectPOMapper;
import org.fu.crowd.po.AddressPO;
import org.fu.crowd.po.AddressPOExample;
import org.fu.crowd.po.OrderPO;
import org.fu.crowd.po.OrderProjectPO;
import org.fu.crowd.service.api.OrderService;
import org.fu.crowd.vo.AddressVO;
import org.fu.crowd.vo.OrderProjectVO;
import org.fu.crowd.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service
@Transactional(readOnly = true)
public class OrderServiceImpl implements OrderService {


    @Resource
    private OrderProjectPOMapper orderProjectPOMapper;

    @Resource
    private OrderPOMapper orderPOMapper;

    @Resource
    private AddressPOMapper addressPOMapper;


    @Override
    public OrderProjectVO getOrderProjectVO(Integer projectId, Integer returnId) {
        OrderProjectVO orderProjectVO = orderProjectPOMapper.selectOrderProjectVO(returnId);
        return orderProjectVO;
    }




    @Override
    public List<AddressVO> getAddressVOList(Integer memberId) {
        AddressPOExample addressPOExample = new AddressPOExample();
        addressPOExample.createCriteria().andMemberIdEqualTo(memberId);
        List<AddressPO> addressPOS = addressPOMapper.selectByExample(addressPOExample);
        List<AddressVO> addressVOList = new ArrayList<>();
        for (AddressPO addressPO : addressPOS){
            AddressVO addressVO = new AddressVO();
            BeanUtils.copyProperties(addressPO,addressVO);
            addressVOList.add(addressVO);
        }
        return addressVOList;
    }







    @Override
    @Transactional(readOnly = false,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public void saveAddress(AddressVO addressVO) {
        AddressPO addressPO = new AddressPO();
        BeanUtils.copyProperties(addressVO,addressPO);
        addressPOMapper.insert(addressPO);
    }






    @Override
    @Transactional(readOnly = false,propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
    public void saveOrder(OrderVO orderVO) {
        OrderPO orderPO = new OrderPO();
        BeanUtils.copyProperties(orderVO,orderPO);
        OrderProjectPO projectPO = new OrderProjectPO();
        BeanUtils.copyProperties(orderVO.getOrderProjectVO(),projectPO);
        int id = orderPOMapper.insert(orderPO);
        projectPO.setId(id);
        orderProjectPOMapper.insert(projectPO);
    }
}
